package com.cloudxingkong.dianyinke.NewTeacher.Ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.GeneralClickListener;
import com.cloudxingkong.dianyinke.NewTeacher.Adapter.UVAdapter;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.LoginJsonUtils;
import com.cloudxingkong.dianyinke.NewTeacher.bean.TeacherVideos;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.NewTeacher.bean.UVTest;
import com.cloudxingkong.dianyinke.Student.Utils.MySwipeView;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class UploadVideo extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, UVAdapter.onTouchVideoDel {

    private ListView listview;

    private List<TeacherVideos.ListBean> datas;
    private View headView;
    private LinearLayout layoutUpLoad;
    private SwipeRefreshLayout refreshLayout;
    private SharedPreferences sharedPreferences;
    private String sessionID;

    private ProgressDialog progressDialog;
    private static final int GET_VIDEO=310;
    private static final int RESULT_VIDEO=311;
    private UVAdapter uvAdapter;

    private boolean isDel=false;
    private TextView tvMsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_video);
        init();
        //填充适配器
        uvAdapter = new UVAdapter(datas,this,listview,this);
        listview.setAdapter(uvAdapter);

        refreshLayout.setOnRefreshListener(this);
        headView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(UploadVideo.this,UploadingVideo.class),GET_VIDEO);
            }
        });

        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
            }
        });
        onRefresh();


    }

    private void loadData() {
        RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + ThisUri.THIS_LIST_VIDEO);
        params.addHeader("cookie",sessionID);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("test","老师拉取视频列表 ： "+result);
                Message msg=handler.obtainMessage();
                msg.what=1;
                msg.obj=result;
                handler.sendMessage(msg);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                refreshLayout.setRefreshing(false);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void init() {
        layoutUpLoad = (LinearLayout) findViewById(R.id.uv_upload_layout);
        listview = (ListView) findViewById(R.id.uv_listview);
        datas=new ArrayList<>();
        headView= LayoutInflater.from(this).inflate(R.layout.layout_uploadvideo,null);
        layoutUpLoad.addView(headView);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.uv_swiperefresh);
        refreshLayout.setColorSchemeResources(R.color.colorGreen);
        sharedPreferences = getSharedPreferences("data_dyk", 0);
        sessionID = CookieHelper.getSessionID(sharedPreferences);
        tvMsg = (TextView) findViewById(R.id.video_tv_msg);
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    String result= (String) msg.obj;
                    Gson gson=new Gson();
                    if (result != null && !result.equals("")) {
                        tvMsg.setVisibility(View.GONE);
                        TeacherVideos teacherVideos = gson.fromJson(result, TeacherVideos.class);
                        if (teacherVideos.getList() != null && teacherVideos.getList().size() > 0) {
                            datas.addAll(teacherVideos.getList());
                            uvAdapter.notifyDataSetChanged();
                        }else{
                            tvMsg.setVisibility(View.VISIBLE);
                        }
                    }else{
                        tvMsg.setVisibility(View.VISIBLE);
                    }

                    refreshLayout.setRefreshing(false);
                    break;
                case 2:
                    progressDialog.dismiss();
                    Toast.makeText(UploadVideo.this, "删除成功！", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    progressDialog.dismiss();
                    Toast.makeText(UploadVideo.this, "删除失败，请重试!", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode==GET_VIDEO){
            switch (resultCode){
                case RESULT_VIDEO:
                    refreshLayout.setRefreshing(true);
                    onRefresh();
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void back(View view) {
        switch (view.getId()){
            case R.id.uv_back:
                finish();
                break;
        }
    }

    @Override
    public void onRefresh() {
        datas.clear();
        loadData();
    }

    @Override
    public void onTouchDel(TextView tvDel,final int position) {
        tvDel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(final View v) {
                progressDialog = ProgressDialog.show(UploadVideo.this, null, "正在删除...", true, false);
                int id = datas.get(position).getId();
                RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + ThisUri.VIDEO_DEL);
                params.addHeader("cookie",sessionID);
                params.addBodyParameter("id", id + "");
                x.http().post(params, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        Log.e("test", "老师删除视频结果 : " + result);
                        HashMap<String, Object> fromLogin = LoginJsonUtils.getJsonFromLogin(result);
                        Object success = fromLogin.get("success");
                        isDel= (boolean) success;

                        if (isDel==true){
                            //删除条目
                            String pos= (String) v.getTag();
                            ((MySwipeView) v.getParent()).quickClose();
                            datas.remove(Integer.parseInt(pos));
                            uvAdapter.notifyDataSetChanged();
                            handler.sendEmptyMessage(2);
                        }else{
                            handler.sendEmptyMessage(3);
                        }

                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        progressDialog.dismiss();
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
            }
        });

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(UploadVideo.this,UVDetail.class);
                intent.putExtra("vTitle",datas.get(position).getTitle());
                intent.putExtra("vMemname",datas.get(position).getMemname());
                intent.putExtra("vViews",datas.get(position).getViews()+"");
                intent.putExtra("vLikes",datas.get(position).getLikes()+"");
                intent.putExtra("vNote",datas.get(position).getNote());
                intent.putExtra("vPath",datas.get(position).getPath());
                intent.putExtra("vID",datas.get(position).getId()+"");
                intent.putExtra("vCover", datas.get(position).getCoverpic() + "");
                if (datas.get(position).getAvatar()!=null){
                    intent.putExtra("vAvatar",datas.get(position).getAvatar());
                }
                startActivity(intent);
            }
        });

    }
}
